package com.peanut.web.controller.user;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.peanut.helper.user.UserHelper;
import com.peanut.helper.user.UserValidateHelper;
import com.peanut.model.user.User;
import com.peanut.search.user.UserSearch;
import com.peanut.service.message.IMessageSendService;
import com.peanut.service.user.IUserService;
import com.peanut.service.user.LoginParam;
import com.peanut.service.user.LoginResponse;
import com.peanut.system.SystemConstant;
import com.peanut.util.StringUtil;
import com.peanut.util.encryption.MD5;
import com.peanut.util.operation.OperationResult;
import com.peanut.util.operation.StatusCode;
import com.peanut.web.controller.BaseController;
import com.peanut.web.util.ocs.MessageIntervalWebUtil;
import com.peanut.web.util.ocs.OCSCacheWebUtil;
import com.peanut.web.util.ocs.OCSWebKeys;

/**
 * 用户controller
 * 
 * @author songjz
 */
@Api(value = "用户管理", produces = "application/json")
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {
  private Logger logger = LoggerFactory.getLogger(getClass());
  @Resource
  private IUserService userService;
  @Resource
  private IMessageSendService messageSendService;

  /**
   * <pre>
   * 用户登录
   * 请求方式:POST，请求路径:/user/login
   * 请求参数：
   *          username     用户名(手机号or邮箱or昵称) 必填
   *          password     密码 必填
   * 返回数据：
   *          userId  用户主键
   * </pre>
   * 
   * @param username
   * @param password
   * @param request
   * @return
   */
  @ApiOperation(value = "用户登录", httpMethod = "POST")
  @RequestMapping(value = "/login", method = { RequestMethod.POST })
  @ResponseBody
  public String login(@RequestParam(value = "username") String username,
      @RequestParam(value = "password") String password, HttpServletRequest request) {
    if (!UserValidateHelper.validateLoginParam(username, password)) {
      return OperationResult.fail(StatusCode.USER_LOGIN_DATA_IS_EMPTY);
    }
    LoginParam loginParam = UserHelper.buildLoginParam(username, password, request);
    LoginResponse loginResponse = userService.login(loginParam);
    if (StringUtil.isNotBlank(loginResponse.message)) {
      OperationResult.fail(loginResponse.message, loginResponse.code);
    }
    // 将用户信息保存到缓存当中
    OCSCacheWebUtil.cacheUser(request, loginResponse.user);;
    Map<String, Object> map = new HashMap<String, Object>(2);
    map.put("userId", loginResponse.user.getId());
    return OperationResult.success(map);
  }

  /**
   * <pre>
   * 用户退出
   * 请求方式:GET，请求路径:/user/logout
   * 请求参数：
   *          无
   * 返回数据：
   *          默认
   * </pre>
   * 
   * @param request
   * @return
   */
  @ApiOperation(value = "用户退出", httpMethod = "GET")
  @RequestMapping(value = "/logout", method = RequestMethod.GET)
  @ResponseBody
  public String logout(HttpServletRequest request) {
    OCSCacheWebUtil.deleteCacheUser(request);
    return OperationResult.success();
  }

  /**
   * <pre>
   * 用户注册
   * 请求方式:POST，请求路径:/user/register
   * 请求参数:
   *          mobile 用户手机号 必填
   *          password 密码 必填
   *          code 验证码 必填
   * 返回数据:
   *          userId  用户主键
   * </pre>
   * 
   * @param mobile
   * @param password
   * @param code
   * @param request
   * @return
   */
  @ApiOperation(value = "用户注册", httpMethod = "POST")
  @RequestMapping(value = { "/register" }, method = { RequestMethod.POST })
  @ResponseBody
  public String register(@RequestParam(value = "mobile", required = true) String mobile,
      @RequestParam(value = "password", required = true) String password, String code, HttpServletRequest request) {
    User user = new User();
    user.setMobile(mobile);
    user.setPassword(MD5.encodeByMd5AndSalt(password));
    user.setNickName(mobile);
    long userId = userService.add(user);
    Map<String, Object> map = new HashMap<String, Object>(2);
    map.put("userId", userId);
    return OperationResult.success(map);
  }

  /**
   * <pre>
   * 用户注册-发送验证码
   * 请求方式:POST，请求路径:/user/registerCode
   * 请求参数：
   *        mobile 手机号 必填
   * 返回数据：
   *        messageInterval 间隔时间秒
   * </pre>
   * 
   * @param mobile
   * @param request
   * @return {messageInterval: 60}
   */
  @RequestMapping(value = "/registerCode", method = { RequestMethod.POST })
  @ResponseBody
  public String registerCode(@RequestParam(value = "mobile") String mobile, HttpServletRequest request) {
    UserSearch userSearch = new UserSearch();
    userSearch.setMobile(mobile);
    long count = userService.findUsersCount(userSearch);
    if (count > 0) {
      return OperationResult.fail(StatusCode.USER_MOBILE_REPEAT);
    }
    // 防止用户在页面载入获取验证码间隔时间时，点击发送验证码
    if (!MessageIntervalWebUtil.varify(mobile)) {
      return OperationResult.fail(StatusCode.SYSTEM_CODE_IS_SENT);
    }
    String code = setVerificationcode(OCSWebKeys.PEANUT_WEB_REGISTER_CODE, request);
    String message = String.format("验证码: %s，请您及时完成验证，如非本人操作请忽略此短信，如需帮助请拨打：%s", code,
        SystemConstant.getInstance().phoneService);
    logger.info(message);
    // 开始发送验证码
    messageSendService.sendSMS(mobile, message);
    Map<String, Object> returnData = new HashMap<String, Object>();
    returnData.put("messageInterval", OCSWebKeys.PEANUT_WEB_MESSAGE_INTERNAL_EXP);
    return OperationResult.success(returnData);
  }

  /**
   * <pre>
   * 用户查询
   * 请求方式:POST，请求路径:/user/query
   * 请求参数：
   *        见userSearch对象
   * 返回数据：
   * [{
   * 
   * }]
   * </pre>
   * 
   * @param search
   * @param request
   * @return
   */
  @RequestMapping(value = "/query", method = { RequestMethod.POST })
  @ResponseBody
  public String query(UserSearch search, HttpServletRequest request) {
    List<User> userList = userService.findUsers(search, null);
    return OperationResult.success(userList);
  }

  /**
   * <pre>
   * 用户查询
   * 请求方式:POST，请求路径:/user/modify
   * 请求参数：
   *        
   * 返回数据：
   *        默认
   * </pre>
   * 
   * @param user
   * @param request
   * @return
   */
  @RequestMapping(value = "/modify", method = { RequestMethod.POST })
  @ResponseBody
  public String modify(User user, HttpServletRequest request) {
    userService.update(user);
    return OperationResult.success();
  }

  /**
   * <pre>
   * 用户详情
   * 请求方式:GET，请求路径:/user/detail
   * 请求参数：
   *          无
   * 返回数据：
   * {
   * }
   * </pre>
   * 
   * @param request
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/detail", method = RequestMethod.GET)
  @ResponseBody
  public String detail(HttpServletRequest request) throws Exception {
    Long userId = getCurrentUserId(request);
    User user = userService.getById(userId);
    return OperationResult.success(UserHelper.toVo(user));
  }
}
